import csv
import json

def csv_to_json(csv_file):
    data = {}
    
    with open(csv_file, 'r', encoding='utf-8-sig') as f:
        reader = csv.reader(f, delimiter=',')
        headers = next(reader)  # Read the header row
        
        current_partition = None
        current_subpart_1 = None
        
        for row in reader:
            partition = row[0].strip()  # First column as partition
            subpart_1 = row[1].strip() if len(row) > 1 else None  # Second column as subpart 1
            subpart_2_raw = row[3].strip() if len(row) > 2 else None  # Fourth column as subpart 2
            
            if partition:
                current_partition = partition
                data[current_partition] = {}
            
            if subpart_1 and current_partition:
                current_subpart_1 = subpart_1
                data[current_partition][current_subpart_1] = []
            
            if subpart_2_raw and current_partition and current_subpart_1:
                subpart_2_list = [subpart.strip() for subpart in subpart_2_raw.split('\n')]
                data[current_partition][current_subpart_1].extend(subpart_2_list)
    
    return data  # Return the data dictionary directly

# Function to save JSON to file
def save_json(data, json_file):
    with open(json_file, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)

# Usage example
csv_file = '/Users/rbruuser32/hreca-json/fast_file.csv'  # Replace with your actual CSV file path
json_file = '/Users/rbruuser32/hreca-json/fast_file.json'  # Replace with desired JSON file path

json_data = csv_to_json(csv_file)
save_json(json_data, json_file)
print(f"JSON data saved to {json_file}")
